'use strict'

import express from 'express'
import mongoose from 'mongoose'
import cors from 'cors'
import postsRouter from './routers/postRouter.js'
import usersRouter from './routers/userRouter.js'
import fileUpload from 'express-fileupload'
import fs from 'fs'

const PORT = 5000
const DB_URL = fs.readFileSync('DB_URL.txt', 'utf8')
const app = express()

app.use(express.json())
app.use(cors())
app.use(fileUpload())
app.use('/api', postsRouter)
app.use('/api', usersRouter)
app.use(express.static('static'))
app.use(express.static('static/pictures'))

const startApp = async () => {
  try {
    await mongoose.connect(DB_URL, {
      useUnifiedTopology: true,
      useNewUrlParser: true,
      useFindAndModify: false
    })
    app.listen(PORT, () => {
      console.log(`server started on port ${PORT} OK`)
    })
  } catch (error) {
    console.log(error)
  }
}

startApp()